'use strict'
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
const morgan = require('morgan'); // display log on the console
var mongoose = require('mongoose');
const mlaburl = "mongodb://liqin:Liqin_123@ds031551.mlab.com:31551/"
const mlabdbname = 'showdb';
const config = require('./config');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
const usemLab = true;
const useatlas = false;
var PORT = 5000;
var dbURI = mlaburl + mlabdbname;
    
let port = process.env.PORT || PORT;
// var path = require('path');
// global.appRoot = path.resolve(__dirname);

//connect to MongoDB
// mongoose.connect('mongodb://localhost/testForAuth');
// var db = mongoose.connection;
console.log('dbURI:::'+dbURI)
mongoose.Promise = global.Promise;
// mongoose.connect(db, {useNewUrlParser: true},{useMongoClient:true}); // 连接数据库
// Create a model and insert a new doc
const conn = mongoose.createConnection(dbURI, {
    useMongoClient: true
  });
const Test = mongoose.model('Test', new mongoose.Schema({ name: String }));
Test.create({ name: 'Val' }).then(doc => console.log(doc));
//handle mongo error
// db.on('error', console.error.bind(console, 'connection error:'));
// db.once('open', function () {
//   console.log("we are connected!")
// });

//use sessions for tracking logins
app.use(session({
  secret: 'work hard',
  resave: true,
  saveUninitialized: false,
  // store: new MongoStore({
  //   mongooseConnection: db
  // })
}));

// parse incoming requests
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));


// serve static files from template
app.use(express.static(__dirname + '/templateLogReg'));

// include routes
var routes = require('./routes/router');
app.use('/', routes);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('File Not Found');
  err.status = 404;
  next(err);
});

// error handler
// define as the last app.use callback
app.use(function (err, req, res, next) {
  res.status(err.status || 500);
  res.send(err.message);
});


// listen on port 3000
app.listen(port, function () {
  console.log('Express app listening on port %s',port);
});

// CONNECTION EVENTS
// When successfully connected
mongoose.connection.on('connected', function () {  
  console.log('Mongoose default connection open to ' + dbURI);
}); 

// If the connection throws an error
mongoose.connection.on('error',function (err) {  
  console.log('Mongoose default connection error: ' + err);
}); 

// When the connection is disconnected
mongoose.connection.on('disconnected', function () {  
  console.log('Mongoose default connection disconnected'); 
});

// If the Node process ends, close the Mongoose connection 
process.on('SIGINT', function() {  
  mongoose.connection.close(function () { 
    console.log('Mongoose default connection disconnected through app termination'); 
    process.exit(0); 
  }); 
}); 